

from quant_researcher.quant.datasource_fetch.crypto_api.glassnode import get_prices
from quant_researcher.quant.project_tool.time_tool import str_to_timestamp
from quant_researcher.quant.project_tool.time_tool import get_yesterday
import datetime
import time
from datetime import timezone
from utils import df_into_db, read_sql
import pandas as pd
import requests

def get_price():
    # url = "https://api.binance.com/api/v1/klines"
    start_date = '2012-12-31'

    yesterday = datetime.datetime.today() - datetime.timedelta(days=1)
    end_date = yesterday.date().strftime('%Y-%m-%d')
    kline = get_prices(ohlc=True, asset='BTC', start_date=start_date, end_date=end_date, interval='24h')
    kline = kline.reset_index(drop=False)
    kline.rename(columns={"end_date": "datetime"}, inplace=True)
    kline["datasource"] = "glassnode"
    kline["frequency"] = "1d"
    kline["timestamp"] = kline["datetime"].apply(lambda x: str_to_timestamp(x, tz_str='+0000')*1000)
    df_into_db(kline, db_name="all_history_ohlcvm_coinmarketcap", table_name="k_line")


def utc_str_to_timestamp(str_time):
    # like"2013-01-01 00:00:00"
    dt = datetime.datetime.strptime(str_time, "%Y-%m-%d %H:%M:%S")
    utc_dt = dt.replace(tzinfo=timezone.utc)
    return int(utc_dt.timestamp())



def get_price_1h():
    start_date = '2012-12-31'

    yesterday = datetime.datetime.today() - datetime.timedelta(days=1)
    end_date = yesterday.date().strftime('%Y-%m-%d')
    kline = get_prices(ohlc=True, asset='BTC', start_date=start_date, end_date=end_date, interval='1h')
    kline = kline.reset_index(drop=False)
    kline.rename(columns={"end_date": "datetime"}, inplace=True)
    kline["datasource"] = "glassnode"
    kline["frequency"] = "1h"
    kline["timestamp"] = kline["datetime"].apply(lambda x: utc_str_to_timestamp(x)*1000)
    df_into_db(kline, db_name="all_history_ohlcvm_coinmarketcap", table_name="k_line")


def get_price_10m():
    start_date = '2012-12-31'

    yesterday = datetime.datetime.today() - datetime.timedelta(days=1)
    end_date = yesterday.date().strftime('%Y-%m-%d')
    kline = get_prices(ohlc=True, asset='BTC', start_date=start_date, end_date=end_date, interval='10m')
    kline = kline.reset_index(drop=False)
    kline.rename(columns={"end_date": "datetime"}, inplace=True)
    kline["datasource"] = "glassnode"
    kline["frequency"] = "10m"
    kline["type"] = "index"
    kline["timestamp"] = kline["datetime"].apply(lambda x: utc_str_to_timestamp(x)*1000)
    df_into_db(kline, db_name="all_history_ohlcvm_coinmarketcap", table_name="k_line")


def timestamp_to_utc_str(timestamp, fmt="%Y-%m-%d %H:%M:%S"):
    """
    将时间戳转换为UTC时间字符串

    参数:
        timestamp: Unix时间戳（秒级）=]
        fmt: 输出字符串的格式
    返回:
        str: UTC时间字符串
    """
    # 创建UTC时间对象
    utc_dt = datetime.datetime.fromtimestamp(timestamp, tz=timezone.utc)

    # 格式化为字符串
    return utc_dt.strftime(fmt)


def get_price_1d_from_binance():
    start_time = 1451606400 * 1000
    all_datas = []
    while True:
        url = f"https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1d&startTime={start_time}&limit=1000"
        response = requests.get(url)
        data = response.json()
        data = [x[:5] for x in data]
        # begin_time = datetime.datetime.fromtimestamp(data[0][0] / 1000)
        # end_time = datetime.datetime.fromtimestamp(data[-1][0] / 1000)
        start_time = data[-1][0]
        all_datas.extend(data)
        if len(data) < 1000:
            break
    all_df = pd.DataFrame(all_datas, columns=["datetime", "open", "high", "low", "close"])
    all_df.rename(columns={"datetime": "timestamp"}, inplace=True)
    all_df["datetime"] = all_df["timestamp"].apply(lambda x: timestamp_to_utc_str(x/1000))
    all_df.drop_duplicates(subset=["timestamp"], keep="last", inplace=True)
    all_df["datasource"] = "binance"
    all_df["frequency"] = "1d"
    df_into_db(all_df, db_name="all_history_ohlcvm_coinmarketcap", table_name="k_line")


def get_price_1h_from_binance():
    start_time = 1451606400 * 1000
    all_datas = []
    while True:
        url = f"https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1h&startTime={start_time}&limit=1000"
        response = requests.get(url)
        data = response.json()
        data = [x[:5] for x in data]
        # begin_time = datetime.datetime.fromtimestamp(data[0][0] / 1000)
        # end_time = datetime.datetime.fromtimestamp(data[-1][0] / 1000)
        start_time = data[-1][0]
        all_datas.extend(data)
        if len(data) < 1000:
            break
    all_df = pd.DataFrame(all_datas, columns=["datetime", "open", "high", "low", "close"])
    all_df.rename(columns={"datetime": "timestamp"}, inplace=True)
    all_df["datetime"] = all_df["timestamp"].apply(lambda x: timestamp_to_utc_str(x/1000))
    all_df.drop_duplicates(subset=["timestamp"], keep="last", inplace=True)
    all_df["datasource"] = "binance"
    all_df["frequency"] = "1h"
    df_into_db(all_df, db_name="all_history_ohlcvm_coinmarketcap", table_name="k_line")


def get_price_5m_from_binance():
    start_time = 1451606400 * 1000
    all_datas = []
    while True:
        print(start_time)
        url = f"https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=5m&startTime={start_time}&limit=1000"
        response = requests.get(url, timeout=10)
        data = response.json()
        data = [x[:5] for x in data]
        # begin_time = datetime.datetime.fromtimestamp(data[0][0] / 1000)
        # end_time = datetime.datetime.fromtimestamp(data[-1][0] / 1000)
        start_time = data[-1][0]
        all_datas.extend(data)
        if len(data) < 1000:
            break
    all_df = pd.DataFrame(all_datas, columns=["datetime", "open", "high", "low", "close"])
    all_df.rename(columns={"datetime": "timestamp"}, inplace=True)
    all_df["datetime"] = all_df["timestamp"].apply(lambda x: timestamp_to_utc_str(x/1000))
    all_df.drop_duplicates(subset=["timestamp"], keep="last", inplace=True)
    all_df["datasource"] = "binance"
    all_df["frequency"] = "5m"
    all_df["type"] = "spot"
    df_into_db(all_df, db_name="all_history_ohlcvm_coinmarketcap", table_name="k_line")


def get_kline_from_binance_with_vol(end_time, frequency="1h"):
    assert frequency in ["1h", "5m", "1d"]
    start_time = 1451606400 * 1000  # utc时间: 2016-01-01 00:00:00
    all_datas = []
    while True:
        print(datetime.datetime.fromtimestamp(start_time / 1000))
        limit = 1000   # binance一次性最多可以拿1000条
        try:
            url = f"https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval={frequency}&startTime={start_time}&limit={limit}"
            response = requests.get(url)
        except Exception as e:
            print(e)
            time.sleep(10)
            continue
        if response.status_code != 200:
            continue
        data = response.json()
        data = [x[:6] + x[7:8] for x in data]
        # begin_time = datetime.datetime.fromtimestamp(data[0][0] / 1000)
        # end_time = datetime.datetime.fromtimestamp(data[-1][0] / 1000)
        start_time = data[-1][0]
        all_datas.extend(data)
        if len(data) < 1000:
            break
    all_df = pd.DataFrame(all_datas, columns=["datetime", "open", "high", "low", "close", "vol", "amount"])
    all_df.rename(columns={"datetime": "timestamp"}, inplace=True)
    all_df["datetime"] = all_df["timestamp"].apply(lambda x: timestamp_to_utc_str(x/1000))
    all_df.drop_duplicates(subset=["timestamp"], keep="last", inplace=True)
    all_df["datasource"] = "binance"
    all_df["frequency"] = frequency
    all_df["type"] = "spot"
    all_df = all_df[all_df["timestamp"] <= end_time]
    df_into_db(all_df, db_name="all_history_ohlcvm_coinmarketcap", table_name="k_line")


def insert_1h_kline_binance():
    start_time = 1451606400 * 1000
    all_datas = []
    while True:
        url = f"https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1h&startTime={start_time}&endTime={1679666400000}&limit=1000"
        response = requests.get(url)
        data = response.json()
        data = [x[:5] for x in data]
        # begin_time = datetime.datetime.fromtimestamp(data[0][0] / 1000)
        # end_time = datetime.datetime.fromtimestamp(data[-1][0] / 1000)
        start_time = data[-1][0]
        all_datas.extend(data)
        if len(data) < 1000:
            break
    all_df = pd.DataFrame(all_datas, columns=["datetime", "open", "high", "low", "close"])
    all_df.rename(columns={"datetime": "timestamp"}, inplace=True)
    all_df["datetime"] = all_df["timestamp"].apply(lambda x: timestamp_to_utc_str(x/1000))
    all_df.drop_duplicates(subset=["timestamp"], keep="last", inplace=True)
    all_df["datasource"] = "binance"
    all_df["frequency"] = "1h"
    df_into_db(all_df, db_name="all_history_ohlcvm_coinmarketcap", table_name="k_line")


def get_price_1d_from_okx(type="index", start_time=1757894400 * 1000):
    all_datas = []
    while True:
        if type == "index":
            url = f"https://www.okx.com/api/v5/market/history-index-candles?instId=BTC-USDT&after={start_time}&bar=1Dutc&limit=100"
        elif type == "spot":
            url = f"https://www.okx.com/api/v5/market/history-candles?instId=BTC-USDT&after={start_time}&bar=1Dutc&limit=100"
        else:
            raise ValueError("无效的type")
        response = requests.get(url)
        if type == "index":
            index_data = response.json()["data"]
        else:
            index_data = response.json()["data"]
            index_data = [x[:5] + x[-1:] for x in index_data]
        start_time = index_data[-1][0]
        all_datas.extend(index_data)
        if len(index_data) < 100:
            break
        time.sleep(0.4)
    index_df = pd.DataFrame(all_datas)
    index_df.columns = ["timestamp", "open", "high", "low", "close", "confirm"]
    index_df = index_df[index_df["confirm"] == '1']
    del index_df["confirm"]
    index_df['frequency'] = '1d'
    index_df['type'] = 'spot'
    index_df["datetime"] = index_df["timestamp"].apply(lambda x: timestamp_to_utc_str(int(x) / 1000))
    print("drop前长度:", len(index_df))
    index_df.drop_duplicates(subset=["timestamp"], keep="last", inplace=True)
    print("drop后长度:", len(index_df))
    index_df["datasource"] = "okx"
    df_into_db(index_df, db_name="all_history_ohlcvm_coinmarketcap", table_name="k_line")


def get_price_1h_from_okx(type, start_time, frequency="1h"):
    # start_time = 1757894400 * 1000  # 2025-09-15 08:00:00+08:00
    all_datas = []
    frequency_map = {"1h": "1H",
                     "5m": "5m",
                     "1d": "1Dutc"}
    bar = frequency_map[frequency]
    while True:
        print(start_time)
        if type == "index":
            url = f"https://www.okx.com/api/v5/market/history-index-candles?instId=BTC-USDT&after={start_time}&bar={bar}&limit=300"
        elif type == "spot":
            url = f"https://www.okx.com/api/v5/market/history-candles?instId=BTC-USDT&after={start_time}&bar={bar}&limit=300"
        else:
            raise ValueError("无效的type")
        try:
            response = requests.get(url)
        except Exception as e:
            print(e)
            time.sleep(10)
            continue
        if type == "index":
            index_data = response.json()["data"]
        else:
            index_data = response.json()["data"]
            index_data = [x[:5] + x[-1:] for x in index_data]
        if not index_data:
            break
        start_time = index_data[-1][0]
        all_datas.extend(index_data)
        if len(index_data) < 100:
            break
        time.sleep(0.1)
    index_df = pd.DataFrame(all_datas)
    index_df.columns = ["timestamp", "open", "high", "low", "close", "confirm"]
    index_df = index_df[index_df["confirm"] == '1']
    del index_df["confirm"]
    index_df['frequency'] = frequency
    index_df['type'] = 'spot'
    index_df["datetime"] = index_df["timestamp"].apply(lambda x: timestamp_to_utc_str(int(x) / 1000))
    print("drop前长度:", len(index_df))
    index_df.drop_duplicates(subset=["timestamp"], keep="last", inplace=True)
    print("drop后长度:", len(index_df))
    index_df["datasource"] = "okx"
    df_into_db(index_df, db_name="all_history_ohlcvm_coinmarketcap", table_name="k_line")


def get_kline_from_okx_with_vol(end_time, frequency="1h"):
    """
{
    "code":"0",
    "msg":"",
    "data":[
     [
        "1597026383085", # 开始时间
        "3.721", # open
        "3.743", # high
        "3.677", # low
        "3.708", # close
        "8422410", # 如果是衍生品合约，数值为合约的张数。如果是币币/币币杠杆，数值为交易货币的数量。
        "22698348.04828491",  # 如果是衍生品合约，数值为交易货币的数量。如果是币币/币币杠杆，数值为计价货币的数量。
        "12698348.04828491",  # 交易量，以计价货币为单位
        "1"
    ],
    [
        "1597026383085",
        "3.731",
        "3.799",
        "3.494",
        "3.72",
        "24912403",
        "67632347.24399722",
        "37632347.24399722",
        "1"
    ]
    ]
}
    """

    start_time = utc_str_to_timestamp(datetime.date.today().strftime('%Y-%m-%d %H:%M:%S'))*1000

    all_datas = []
    frequency_map = {"1h": "1H",
                     "5m": "5m",
                     "1d": "1Dutc"}
    bar = frequency_map[frequency]
    while True:
        print(datetime.datetime.fromtimestamp(int(start_time) / 1000))
        limit = 300  # okx最大支持的返回条数
        url = f"https://www.okx.com/api/v5/market/history-candles?instId=BTC-USDT&after={start_time}&bar={bar}&limit={limit}"
        try:
            response = requests.get(url)
        except Exception as e:
            print(e)
            time.sleep(10)
            continue
        if response.status_code != 200:
            print("返回的状态码不对")
            time.sleep(10)
            continue
        data = response.json()["data"]
        if not data:
            break
        start_time = min(data[-1][0], data[0][0])
        all_datas.extend(data)
        if len(data) < 100:
            break
    all_df = pd.DataFrame(all_datas)
    all_df.columns = ["timestamp", "open", "high", "low", "close", "vol", "amount", "amount2", "confirm"]
    assert all_df["amount"].equals(all_df["amount2"]), "btc/usdt报价货币和计价货币都是USDT"
    all_df = all_df[all_df["confirm"] == '1']
    del all_df["confirm"], all_df["amount2"]
    all_df['frequency'] = frequency
    all_df['type'] = 'spot'
    all_df["datetime"] = all_df["timestamp"].apply(lambda x: timestamp_to_utc_str(int(x) / 1000))
    print("drop前长度:", len(all_df))
    all_df.drop_duplicates(subset=["timestamp"], keep="last", inplace=True)
    print("drop后长度:", len(all_df))
    all_df["datasource"] = "okx"
    all_df = all_df[all_df["timestamp"] <= str(end_time)]
    df_into_db(all_df, db_name="all_history_ohlcvm_coinmarketcap", table_name="k_line")


def merge_two_datasoure_kline(fequency="1h"):
    df = read_sql(f"select * from k_line where symbol='BTC' and frequency='{fequency}'", db_name="all_history_ohlcvm_coinmarketcap")
    binance_df = df[df["datasource"] == "binance"]
    binance_begin_time = datetime.datetime(2018, 1, 1)
    binance_df = binance_df.loc[binance_df['datetime'] >= binance_begin_time]
    glassnode_df = df[df["datasource"] == "glassnode"]
    glassnode_begin_time = datetime.datetime(2016, 1, 1)
    glassnode_end_time = datetime.datetime(2018, 1, 1)
    glassnode_df = glassnode_df[(glassnode_df['datetime'] >= glassnode_begin_time) &
                                (glassnode_df['datetime'] < glassnode_end_time)]
    columns = ["datetime", "open", "high", "low", "close"]
    merge_df = pd.concat([binance_df[columns], glassnode_df[columns]])
    merge_df.sort_values(by=["datetime"], inplace=True)
    return merge_df


def check_okx_data():
    df = read_sql("SELECT * FROM `k_line` where datasource = 'okx' and frequency = '5m' and datetime >= '2018-01-12'",
             db_name="all_history_ohlcvm_coinmarketcap")
    df["date"] = df["datetime"].dt.date
    count_df = df.groupby("date")["date"].count()
    assert all(count_df == 24*12), "每天的5分钟k线不完备"


def check_bitstamp_data(frequency):
    df = read_sql(
        f"select datetime,datasource,vol,amount from k_line where symbol='BTC' and frequency='{frequency}' and datasource ='bitstamp'",
        db_name="all_history_ohlcvm_coinmarketcap")
    df["date"] = df["datetime"].dt.date
    max_date = df["date"].max()
    min_date = df["date"].min()
    df = df[(df["date"] > min_date) & (df["date"] < max_date)]
    count_df = df.groupby("date")["date"].count()
    if frequency == "1h":
        assert all(count_df == 24)
    elif frequency == "5m":
        assert all(count_df == 24*12)
    else:
        raise Exception("invalid frequency")

def try_fill_bitstamp_missing_data():
    df = read_sql("SELECT * FROM `k_line` where datasource = 'bitstamp' and frequency = '5m' ",
             db_name="all_history_ohlcvm_coinmarketcap")
    df["date"] = df["datetime"].dt.date
    df = df[df["date"] > df["date"].min()]  # 剔除第一天的K线, 不完整
    df = df[df["date"] < df["date"].max()]  # 剔除最后一天的K线, 不完整
    df["time"] = df["datetime"].dt.time
    all_times = set(df["time"].unique())
    all_dates = set(df["date"].unique())
    all_datetimes = set([datetime.datetime.combine(x, y) for x in all_dates for y in all_times])
    missing_datetimes = all_datetimes - set(df["datetime"])
    missing_timestamps = [int(x.replace(tzinfo=datetime.timezone.utc).timestamp()) for x in missing_datetimes]
    missing_timestamps.sort()
    base_url = "https://www.bitstamp.net/api/v2/ohlc/btcusd/"
    all_data = []
    count = 0
    for missing_timestamp in missing_timestamps:
        try:
            count += 1
            print(f"{count}/{len(missing_timestamps)}")
            params = {
                'step': 300,  # 300秒 5分钟
                'limit': 3,
                'start': missing_timestamp-300,
            }
            response = requests.get(base_url, params=params, timeout=30)
            data = response.json()
            ohlc = data['data']['ohlc']
            ohlc = [x for x in ohlc if int(x['timestamp']) == missing_timestamp]
            all_data.extend(ohlc)
        except Exception as e:
            print(e)
            continue
    df = pd.DataFrame(all_data)
    df["datetime"] = df["timestamp"].apply(lambda x: timestamp_to_utc_str(int(x)))
    df['timestamp'] = df["timestamp"].apply(lambda x: int(x)*1000)
    df['open'] = df['open'].astype(float)
    df['high'] = df['high'].astype(float)
    df['low'] = df['low'].astype(float)
    df['close'] = df['close'].astype(float)
    df["symbol"] = "BTC"
    df["type"] = "spot"
    df["datasource"] = "bitstamp"
    df["frequency"] = "5m"
    df.drop(columns=["volume"], axis=1, inplace=True)
    print("drop前长度:", len(df))
    df.drop_duplicates(subset=["timestamp"], keep="last", inplace=True)
    print("drop后长度:", len(df))
    df_into_db(df, db_name="all_history_ohlcvm_coinmarketcap", table_name="k_line")


def try_fill_binance_missing_data():
    df = read_sql("SELECT * FROM `k_line` where datasource = 'binance' and frequency = '5m' ",
             db_name="all_history_ohlcvm_coinmarketcap")
    df["date"] = df["datetime"].dt.date
    df = df[df["date"] > df["date"].min()]  # 剔除第一天的K线, 不完整
    df = df[df["date"] < df["date"].max()]  # 剔除最后一天的K线, 不完整
    df["time"] = df["datetime"].dt.time
    all_times = set(df["time"].unique())
    all_dates = set(df["date"].unique())
    all_datetimes = set([datetime.datetime.combine(x, y) for x in all_dates for y in all_times])
    missing_datetimes = all_datetimes - set(df["datetime"])
    missing_timestamps = [int(x.replace(tzinfo=datetime.timezone.utc).timestamp()) for x in missing_datetimes]
    missing_timestamps.sort()
    all_datas = []
    for missing_timestamp in missing_timestamps:
        start_time = (missing_timestamp - 300) * 1000
        url = f"https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=5m&startTime={int(start_time)}&limit=3"
        response = requests.get(url, timeout=10)
        data = response.json()
        data = [x[:5] for x in data]
        ohlc = [x for x in data if x[0] == int(missing_timestamp)*1000]
        all_datas.extend(ohlc)
    assert len(all_datas) == 0


def get_kline_from_bitstamp_with_vol(end_time, frequency):
    base_url = "https://www.bitstamp.net/api/v2/ohlc/btcusd/"
    # start_time = 1262304000  # utc 2020-01-01 00:00:00
    start_time = 1313625600  # utc 2011-08-18 00:00:00
    # start_time = 1313668800  # utc 2011-08-18 12:00:00
    all_datas = []
    frequency_map = {"1h": 3600,
                     "5m": 300,
                     "1d": 3600*24}
    while True:
        print(f"{datetime.datetime.fromtimestamp(int(start_time))}+08:00")
        params = {
            'step': frequency_map[frequency],
            'limit': 1000,
            'start': start_time,
        }
        try:
            response = requests.get(base_url, params=params, timeout=30)
        except Exception as e:
            print(e)
            time.sleep(10)
            continue
        if response.status_code != 200:
            print("返回的状态码不对")
            time.sleep(10)
            continue
        data = response.json()
        ohlc = data['data']['ohlc']
        all_datas.extend(ohlc)
        if len(ohlc) < 1000:
            print(f"start_time: {datetime.datetime.fromtimestamp(int(start_time))}+08:00, 得到的数据长度:{len(ohlc)}")
            if int(ohlc[0]['timestamp']) == start_time:
                print("到达退出条件")
                break
            else:
                print(f"获得的第一条数据时间:{datetime.datetime.fromtimestamp(int(ohlc[0]['timestamp']))}+08:00")
        start_time = int(ohlc[-1]["timestamp"])
    df = pd.DataFrame(all_datas)
    df["datetime"] = df["timestamp"].apply(lambda x: timestamp_to_utc_str(int(x)))
    df['timestamp'] = df["timestamp"].apply(lambda x: int(x)*1000)
    df['open'] = df['open'].astype(float)
    df['high'] = df['high'].astype(float)
    df['low'] = df['low'].astype(float)
    df['close'] = df['close'].astype(float)
    df["symbol"] = "BTC"
    df["type"] = "spot"
    df["datasource"] = "bitstamp"
    df["frequency"] = frequency
    df.rename(columns={"volume":"vol"}, inplace=True)
    print("drop前长度:", len(df))
    df.drop_duplicates(subset=["timestamp"], keep="last", inplace=True)
    print("drop后长度:", len(df))
    df = df[df['timestamp'] <= end_time]
    df_into_db(df, db_name="all_history_ohlcvm_coinmarketcap", table_name="k_line")


def get_kline_with_vol_all():
    start_time = 1759881600 *1000  #  2025-10-08 00:00:00+00:00
    get_kline_from_binance_with_vol(start_time, frequency="1d")
    get_kline_from_binance_with_vol(start_time, frequency="1h")
    get_kline_from_binance_with_vol(start_time, frequency="5m")

    start_time = 1759881600 *1000  #  2025-10-08 00:00:00+00:00
    get_kline_from_okx_with_vol(start_time, "1d")
    get_kline_from_okx_with_vol(start_time, "1h")
    get_kline_from_okx_with_vol(start_time, "5m")

    start_time = 1759881600 *1000  #  2025-10-08 00:00:00+00:00
    get_kline_from_bitstamp_with_vol(start_time, "1d")
    get_kline_from_bitstamp_with_vol(start_time, "1h")
    get_kline_from_bitstamp_with_vol(start_time, "5m")


if __name__ == '__main__':
    # BTC_kline_1d = merge_two_datasoure_kline(fequency="1d")
    # BTC_kline_1d.to_csv("BTC_kline_1d.csv", index=False)
    # BTC_kline_1d = merge_two_datasoure_kline(fequency="1h")
    # BTC_kline_1d.to_csv("BTC_kline_1h.csv", index=False)

    # get_price_1d_from_okx(type="spot")

    # get_price_1h_from_okx(type="index")
    # get_price_1d_from_okx(type="spot", start_time=1633651200* 1000)

    # get_price_1d_from_okx(type="spot", start_time=1633651200*1000)
    # insert_1h_kline_binance()
    # get_price_1h_from_binance_with_vol()
    # get_price_1d_from_binance()

    # get_price_5m_from_binance()
    # get_price_10m()
    # get_price_1h_from_okx(type="spot", start_time=1601804400 * 1000, frequency="5m")
    check_okx_data()
    # try_fill_bitstamp_missing_data()
    # try_fill_missing_data()
    # try_fill_binance_missing_data()

